package com.ydlclass.serialization.jdk;

import com.ydlclass.exception.SerializeException;
import com.ydlclass.serialization.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;


/**
 * @author it楠老师
 * @createTime 2023-03-09
 */
@Slf4j
public class JdkSerializer implements Serializer {
    @Override
    public byte[] serialize(Object obj) {
        if(log.isDebugEnabled()){
            log.debug("Serialization is being done using jdk.");
        }
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(baos)) {
            out.writeObject(obj);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("对象[{}]序列化过程发生了异常！",obj,e);
            throw new SerializeException("An exception occurred while implementing serialization using jdk");
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if(log.isDebugEnabled()){
            log.debug("Deserialization is being done using jdk.");
        }
        try (
            ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bin);
        ){
            Object readObject = ois.readObject();
            return (T)readObject;
        } catch (IOException | ClassNotFoundException e){
            log.error("class[{}]反序列化过程发生了异常！",clazz.getName(),e);
            throw new SerializeException("An exception occurred while implementing deserialization using jdk");
        }
    }

    @Override
    public byte getCode() {
        return 1;
    }
}
